

-module( user_sl ).

-include("emqttd.hrl").

-export([ handle/1 ]).


% -----------------------------------------------------------------------------------
% @doc 注册用户接口
% -----------------------------------------------------------------------------------
handle(Params) ->
    try
        Username = proplists:get_value(<<"username">>,Params, undefined),
        UserId = proplists:get_value(<<"userid">>,Params, undefined),

        case Username =:= undefined orelse UserId =:= undefined of
            true ->
                throw("register Username undefined");
            _NotUndefined ->
                ok
        end,


        util:print("register -> UserId:[~p] UserName:[~p]~n",[ UserId, Username ]),

        Appkey =   <<"wx">>,
    
        {ok,Im} = application:get_env(ham_server, emqttd),

        Users = #users{   user_id = UserId,
                      username = Username,
                      name = Username},

      
        ok = rpc:call(Im, mnesia, dirty_write, [ users, Users] ),
        NewUserInfo = 
        case rpc:call(Im, mnesia, dirty_read,  [ user_info, UserId ] ) of
            [] ->
               #user_info{
                  platform_type = 1,
                  id = UserId,
                  appkey = Appkey  
               };
            [ OldUserInfo ] ->
               OldUserInfo#user_info{
                  id = UserId
               };
            _OthersCantReq ->
               #user_info{
                  platform_type = 1,
                  id = UserId,
                  appkey = Appkey                     
               }
        end,

        ok = rpc:call(Im, mnesia, dirty_write, [ user_info, NewUserInfo] ),
        #user_info{platform_type = PlType} = NewUserInfo,
        case emysql:execute( im_db, "replace into user_info (user_id,user_name, appkey, pltype) values (?,?,?,?) ", [ UserId, Username, Appkey, PlType ] ) of
                {ok_packet, _C, _F, _VL, _E, _L, _L1} ->
                    ok;
                _OthersError ->
                    throw( {mysql_error, _OthersError} )
        end,
        {ok, [{<<"code">>,0}]}
    catch
        M:R ->
            lager:error("register error: ~p ~p ~p~n", [M,R,erlang:get_stacktrace()]),
            {error, [{<<"code">>,5}]}
    end.






